import {
  dom,
  _append,
  _closest,
  _attr
} from './dom.js'
import {
  updateRoute,
  getRoute
} from './route.js'

import { renderContent } from './renderContent.js'
export const _tabs = (config = []) => {
  let {
    tabs,
    activeName
  } = config


  // 初始化路由
  let route = getRoute()
  if (route) {
    activeName = route
  }


  let activeBar = dom.div("", {
    class: 'tabs__active-bar'
  })

  const updateActiveBar = (el, t) => {
    // let rect=el.getBoundingClientRect()
    // console.log(rect)
    // 等dom加载完毕后计算
    setTimeout(() => {
      let offsetLeft = el.offsetLeft
      let width = el.offsetWidth
      activeBar.style = `width:${width}px;transform: translateX(${offsetLeft}px);`
    })

    // 更新路由
    updateRoute(t)
  }
  const isActive = (t) => {
    return t.name === activeName
  }

  let items = tabs.map(t => {
    let item = dom.div(t.title, {
      class: 'tabs__item' + (isActive(t) ? ' active' : ''),
      name: t.name
    }, (e) => {
      let el = e.target
      updateActiveBar(el, t)
      panels.forEach(panel => {
        let role = _attr(panel, "role")
        if (role === t.name) {
          panel.classList.add('active')
        } else {
          panel.classList.remove("active")
        }
      })
    })

    if (isActive(t)) {
      updateActiveBar(item, t)
    }
    return item
  })

  let tabsHeader = dom.div([activeBar, ...items], {
    class: 'tabs__header'
  })

  let panels = tabs.map(t => {
    let { content, isHtml } = renderContent(t)
    let panel = dom.div(content, {
      role: t.name,
      class: 'tabpanel' + (isActive(t) ? ' active' : ''),
      isHtml
    })
    return panel
  })

  let tabsContent = dom.div(panels, {
    class: 'tabs__content'
  })

  let container = dom.div([tabsHeader, tabsContent], {
    class: 'tabs'
  })

  return container
}
